<template>
	<view class="d-kuan ">
		<view decode="true" class="d-kuan d-neirong-juzhong d-shang-30 ">您的余额</view>
		<view decode="true" class="d-kuan d-neirong-juzhong d-shang-10 d-wenzi-30 d-jiacu d-wenzi-yanse-hongse">{{yonghuXinxi.money}}</view>
		<view class="voucher_center__1 d-shang-30">
			    
				<text decode="true" class="voucher_center__47">充值金额</text>
				<view class="voucher_center__48">
					<text decode="true" class="voucher_center__49">￥</text>
					<input :value="money" @input="money_input" @tap="openKeyBoard('number')" class="money" placeholder="0.00" @focus="noKeybord" />
		
				</view>
				<radio-group @change="payType_change" class="payType">
					<image v-on:click="voucher_center__55_55_click()"  src="/static/images/voucher_center__55_55.jpg" mode="scaleToFill" border="0"    class="voucher_center__55"></image>
					<text decode="true" class="voucher_center__56">微信</text>
					<radio value="wx"  class="voucher_center__57" checked>
					</radio>
					<!--image v-on:click="voucher_center__58_58_click()"  src="/static/images/voucher_center__58_58.jpg" mode="scaleToFill" border="0"    class="voucher_center__58"></image>
					<text decode="true" class="voucher_center__59">支付宝</text>
					<radio value="zfb"  class="voucher_center__60">
					</radio-->
				</radio-group>
				<button v-on:click="btSubmit_21_click()" class="btSubmit">确认支付
				</button>
				<view class=" d-clear " >
					<view class=" d-buhuanhang">
						<text  class="voucher_center__66 d-neirong-juzhong" style="display: flex; justify-content: center;"><u-icon v-if="fanhuidata" name="arrow-left" color="#515151" size="28" label="返 回" labelSize="20" @click="fanhui"></u-icon> </text>
						<text  class="voucher_center__66 d-neirong-juzhong" style="display: flex; justify-content: center;"><u-icon name="reload" color="#515151" size="28" label="刷 新" labelSize="20" @click="shuaxin"></u-icon> </text>
					</view>
					
				</view>
				
				<text decode="true" class="voucher_center__22">充值须知</text>
				<text decode="true" class="voucher_center__23">
					{{pay.shuoming}}
				</text>
			</view>
			
			<view class="loading">{{loadingText}}</view>
			<view class="ymBbottom"></view>
			<!-- 数字键盘 -->
			<keyboard ref="number"   @onInput="onInput" @onDelete="onDelete" @onConfirm="onConfirm" :disableDot="true"/>
		    <!--web-view src="https://duixin.cc/index.php?s=member&app=pay&c=recharge&m=index"> 充值 </web-view-->
			<u-popup :show="show" @close="close" @open="open">
				<view >微信扫描支付二维码</view>
				<view style="display: flex; justify-content: center; align-items: center;margin-bottom: 100px;margin-top: 100px;">
					
					<u--image :src="zhifuerweima && zhifuerweima.code" shape="radius" width="150px" height="150px"></u--image>
				</view>
			</u-popup>
			
	</view>
</template>

<script>
	import keyboard from "@/components/keyboard-package/keyboard-package";
	import Api from '@/utils/api.js'; 
	
	
	
	//var wxRequest = require("../../utils/wxRequest.js");
	import { getRequest,postRequest } from '@/utils/wxRequest.js';
	import config from "../../utils/config";
	var pageCount = config.getPageCount;
	var webSiteName = config.getWebsiteName;
	var domain = config.getDomain;
	var banbenhao = config.getDuixinbanbenhao;
	const app = getApp();
	/*#ifdef APP-PLUS || H5*/
		var code = uni.getStorageSync('userInfo');
	/*#endif*/
	/*#ifdef MP-WEIXIN*/
	    var code = uni.getStorageSync('userInfo');
	/*#endif*/
	export default {
	  data() {
	    return {
			pageTitle: '钱包充值',
			webSiteName: webSiteName,
			banbenhao: banbenhao,
			domain: domain,
			member:{},
			yonghuXinxi: [],
			code:code,
			uid:'',
			tongji:{},
			
			loadingText: '',
			animation: '',
			animationData: {},
			money:'',//充值金额
			payType:'wx',//单选框选中值
						
			 
			page:0,//当前分页页码
			apiUrl:'',//后端接口地址
			id:'',//传值使用,方便存在本地的locakStorage  
			del_id:'',//方便存在本地的locakStorage  
			errorMessage: '', // 错误提示信息
			pay:{},
			keycode:'',
			zhifuerweima:{},
			show: false,
			fanhuidata: false,
			fanhuiurl:''
		}
		},
		components: {
		    keyboard, 
			
		},
		onShow: function () {
			  var duixin = this;
			  // 暗黑模式
			  var initialThemes = uni.getStorageSync('theme');
			  if(!initialThemes){
				duixin.fenggeyanse = 'light';
				uni.setStorageSync('theme', 'light');
			  } else {
				duixin.fenggeyanse = initialThemes;
			  }
			  
		
			uni.setNavigationBarColor({
				backgroundColor: this.fenggeyanse =='light'? '#ffffff':'#151515',
				frontColor: this.fenggeyanse =='light'? '#000000':'#ffffff',
			})
			//判断用户是否登录
			var userInfo = uni.getStorageSync('userInfo');

		},
		onLoad: function (options) {
			var self = this; 
			var duixin = this; 
			uni.reLaunch();
			duixin.getPayshuomingdata();
			//判断用户是否登录
			var userInfo = uni.getStorageSync('userInfo');
			var keycode = uni.getStorageSync('keycode');
			// 分段是否有返回的url
			var fanhuiurl = uni.getStorageSync('fanhuiurl');
			
			if(fanhuiurl) {
				duixin.fanhuidata = true;
				duixin.fanhuiurl = fanhuiurl;
			}
			duixin.keycode = keycode;
			if (userInfo) {
				this.showuid = true;
				var member = uni.getStorageSync('member');
				var memberuid = uni.getStorageSync('memberuid');
				//self.uid = memberuid;
				duixin.uid = memberuid;
				duixin.getYonghuXinxi(memberuid);
				
			} else {
				//否则跳转到登录页面
				uni.reLaunch({ url: '/pages/login/login'}) // 跳转到首页
			}
		},
		
		onReady: function () {
		  uni.setNavigationBarTitle({
		    title: this.pageTitle
		  });
		},
		methods: {
			openKeyBoard(key) {
				this.type=key;
				this.$refs[key].open();
			},
			onInput(val){
				this.money += val;
			},
			onDelete(){
				if (this.money.length > 0) {  
					this.money = this.money.slice(0, -1);  
				}
			},
			/**
			* btSubmit_21处理函数
			* 数据绑定  data-index="{{index}}" 
			* 数据取值  var index = e.currentTarget.dataset.index; var cata = this.list_cata_list[index];
			*/
			btSubmit_21_click:function(event){
				var duixin = this;
				  if(this.money==''){
					  uni.showToast({title: '充值金额不能为空！',icon: 'none',duration: 2000});
					 return; 
				  } else if (this.payType==''){
					  uni.showToast({title: '充值方式不能为空！',icon: 'none',duration: 2000});
					 return; 
				  } else {
					  /*uni.showToast({title: '开始充值',icon: 'none',duration: 2000});
					  return; */
					  duixin.chongzhipay();
				  }
			},
			/**
			* radio处理函数
			*/
			payType_change:function(event){
			    //console.log(event.target.value);
			    this.payType=event.target.value;
			},
			/**
			* input处理函数
			*/
			money_input:function(event){
			    this.money=event.target.value;
				const regex = /^\d+(\.\d{1,2})?$/; // 匹配整数或小数（最多两位小数)
				var value = this.money;
				if (!regex.test(this.money)) {  
					this.money = '';
					this.errorMessage = '请输入数字和点（.）';
					uni.showToast({title: '请输入数字',icon: 'none',duration: 2000});
					return; 
				// 清除非法输入，保持上一个合法值  
				//this.money = value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/\.$/, '');  
				} else {  
					this.errorMessage = '';  
				} 
			    //console.log(event.target.value);
			},
			// 充值说明
			getPayshuomingdata(){
				var duixin = this;
				//console.log('xx'); 
				var getPayshuomingRequest = getRequest(Api.getPayshuoming());
				getPayshuomingRequest.then(response => {
					if (response.data.code == 1) {
					  //console.log(response.data.data); 
					  duixin.pay = response.data.data
					} else {
					  duixin.setData({
						displaySwiper: "none"
					  });
					}
				});
			},
			//会员信息
			getYonghuXinxi(uid) {
				var duixin = this; 
				var getYonghuXinxiRequest = getRequest(Api.getYonghuXinxi(uid));
				getYonghuXinxiRequest.then(response => {
					if (response.data.code == 1) {
					  duixin.yonghuXinxi = response.data.data
					} else {
					  duixin.setData({
						displaySwiper: "none"
					  });
					}
				});
			},
			//数字键盘的确定
			onConfirm(){
				
			},
			// 充值
			chongzhipay(){
				/*uni.showToast({title: '开始充值',icon: 'none',duration: 2000});
				return;*/
				var duixin = this; 
				var money = this.money;
				// #ifdef H5
				const userAgent = navigator.userAgent.toLowerCase();
				if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android/.test(userAgent)) {
					// 移动端
					//console.log('移动端',userAgent)
					var h5datas = "is_ajax=1&pay[mark]=recharge&pay[money]=" + money + "&pay[type]=weixin&pay[is_xcx]=1&h5=1";
				} else {
					// pc端
					//console.log('PC端',userAgent)
					var h5datas = "is_ajax=1&pay[mark]=recharge&pay[money]=" + money + "&h5=2";
				}
				// #endif
				

				var datas = "is_ajax=1&pay[mark]=recharge&pay[money]=" + money + "&pay[type]=weixin&pay[is_xcx]=1";
				var uid = this.$store.state.memberuid;
				var keycode = this.$store.state.keycode;
				var postPayRequest = postRequest(Api.postPay(uid,keycode),datas);
				postPayRequest.then(response => {
					if (response.data.code) {
						//console.log('弹出0'); 
						// #ifdef MP
						duixin.getPayzhifu(response.data,datas);
						// #endif
						// #ifdef H5
						duixin.getPayzhifu(response.data,h5datas);
						
						// #endif
						
						
					} else {
						uni.showToast({
							icon: 'none',
							title: response.data.msg,
							duration: 1000
						});
					}
				});
			},
			// 拉起支付
			getPayzhifu(data,urldata){
				//console.log('弹出2');
				var duixin = this; 
				// #ifdef MP
				var getPayidRequest = getRequest(Api.getPayid(data.code,urldata));
				// #endif
				// #ifdef H5
				var getPayidRequest = getRequest(Api.getPayid(data.code,urldata));
				// #endif
				getPayidRequest.then(response => {
					//console.log('支付weixin',response); 
					if (response.data.code) {
						// #ifdef H5
							//duixin.getH5payzhifu(response.data.data,urldata);
							duixin.getWeixinMiyueData(response.data.data);
							if(response.data.data && response.data.data.pc == 1){
								duixin.zhifuerweima = response.data.data;
								duixin.show = true;
							}
						// #endif
						// #ifdef MP
						// 小程序
						wx.requestPayment({
							"timeStamp": response.data.data.timeStamp,
							"nonceStr": response.data.data.nonceStr,
							"package": response.data.data.package,
							"signType": "MD5",
							"paySign": response.data.data.paySign,
							"success":function(res){
								duixin.getMemberpay(res);
							},
							"fail":function(res){
								//console.log(res);
								wx.showModal({
									showCancel: false,
									content: res.err_desc+"："+res.errMsg
								})
							}
							
						})
						// #endif
					  //console.log('支付',response.data); 
					  //duixin.quanzishuxing = response.data.data
					} else {
					  uni.showToast({
					  	icon: 'none',
					  	title: response.data.msg,
					  	duration: 1000
					  });
					}
				});
			},
			
			getWeixinMiyueData(data){
				
				var duixin = this;
				var danqianurls = uni.getLaunchOptionsSync();
				//var danqianurls = '/'+danqianurls.path+'?id='+danqianurls.query.id;
				var danqianurls = '/'+danqianurls.path;
				
				const url = decodeURIComponent(window.location.href);
				var urljia = danqianurls;
				
				var getWeixinmiyueRequest = getRequest(Api.getWeixinfengxiangmiyue(url));
				 
				getWeixinmiyueRequest.then(response => {
					
					if (response.data.code == 1) {
						
						var weixin = response.data.data;
						//console.log('充值H5weixin',weixin);
						duixin.$wx.config({
						  debug: false,//true
						  appId: weixin.appId,
						  timestamp: weixin.timestamp,
						  nonceStr: weixin.nonceStr,
						  signature: weixin.signature,
						  jsApiList: [
						    // 所有要调用的 API 都要加到这个列表中
						    
						    // 这里需要自己按微信文档来写参数
						    "updateAppMessageShareData", 
							"updateTimelineShareData",
							'checkJsApi', //判断当前客户端版本是否支持指定JS接口  
							'onMenuShareAppMessage', //分享接口  
							'getLocation', //获取位置  
							'openLocation', //打开位置  
							'scanQRCode', //扫一扫接口  
							'chooseWXPay', //微信支付  
							'chooseImage', //拍照或从手机相册中选图接口  
							'previewImage', //预览图片接口  
							'uploadImage' //上传图片  
						  ]
						});
						duixin.$wx.ready(function () {
							//duixin.getPayzhifu(dataa,datab);
							//console.log('支付data',data); 
							
							// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
							duixin.$wx.checkJsApi({
								jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
								success: function(res) {
									//console.log('支付res',res); 
								}
							});
							// 调用微信支付接口
							duixin.$wx.chooseWXPay({
								timestamp: data.timeStamp,    // 时间戳
								nonceStr: data.nonceStr,      // 随机串
								package: data.package,        // 订单详情扩展字符串
								signType: 'MD5',                // 签名方式
								paySign: data.paySign,           // 签名
								success: function(res) {
									// 支付成功后的回调函数
									duixin.getMemberpay(res);
								},
								fail: function(res) {
									// 支付失败后的回调函数
									console.error('Payment failed', res);
									
									setTimeout(() => {
										uni.reLaunch({
											url: '/pages/fail/fail'
										})
									}, 500)
								}
							})
							
						});
						duixin.$wx.error(function(res){
						  //console.log('weixinres',res); 
						});
					} else {
					    duixin.setData({
							displaySwiper: "none"
					    });
					}
				});
			},
			
			//h5拉起支付
			getH5payzhifu(data,urldata){
				var duixin = this;
				//console.log('支付weixin',weixin); 
				// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
					duixin.$wx.checkJsApi({
						jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
						success: function(res) {
							//console.log('支付res',res); 
						}
					});
				// 调用微信支付接口
				    duixin.$wx.chooseWXPay({
				        timestamp: data.timeStamp,    // 时间戳
				        nonceStr: data.nonceStr,      // 随机串
				        package: data.package,        // 订单详情扩展字符串
				        signType: 'MD5',                // 签名方式
				        paySign: data.paySign,           // 签名
						success: function(res) {
							// 支付成功后的回调函数
							duixin.getMemberpay(res);
					    },
						fail: function(res) {
							// 支付失败后的回调函数
							console.error('Payment failed', res);
							
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/fail/fail'
								})
							}, 500)
						}
					})
			
			
			},
			//拉起会员
			getMemberpay(data){
				var uid = this.$store.state.memberuid;
				var keycode = this.$store.state.keycode;
				var duixin = this;
				var getMemberidRequest = getRequest(Api.getMemberid(uid,keycode));
				getMemberidRequest.then(res => {
					if (res.data.code == 1) {
						uni.showModal({
							showCancel: false,
							success: function (res) {
							  if (res.confirm) {
                                 /*if(duixin.fanhuiurl){
-                                     uni.reLaunch({ url: duixin.fanhuiurl });
-                                 }
+                                 const targetUrl = duixin.fanhuiurl;
+                                 if (targetUrl && /^\/pages\/[^/]+\/[^/]+/.test(targetUrl)) {
+                                     uni.reLaunch({ url: targetUrl });
+                                 } else {
+                                     // 兜底：无效或空的返回地址，跳转到首页
+                                     uni.reLaunch({ url: '/pages/index/index' });
+                                 }*/
                                
                              }
                            },
                            content: "付款成功"
					    });
					}
				});
			},
			close(){
				this.show = false;
			},
			open(){
				this.show = true;
			},
			fanhui(){
				var duixin = this;
-               /*uni.reLaunch({ url: duixin.fanhuiurl });
+               const targetUrl = duixin.fanhuiurl;
+               if (targetUrl && /^\/pages\/[^/]+\/[^/]+/.test(targetUrl)) {
+                   uni.reLaunch({ url: targetUrl });
+               } else {
+                   // 兜底：无效或空的返回地址，跳转到首页
+                   uni.reLaunch({ url: '/pages/index/index' });
+               }*/
                uni.setStorageSync('fanhuiurl', '');
			},
			shuaxin(){
				setTimeout(() => {
				    this.$router.go(0)
				}, 500)
			},
			noKeybord() {
				document.activeElement.blur(); // 禁止输入框对焦（禁止弹出原生键盘）
				uni.hideKeyboard();
			},
		}
	}
</script>

<style>
	uni-page-body,#app {height: 100%;}
	button::after {border: none;width: auto;}
	input{outline: none;border: none;list-style: none;width: auto;}
	.list_item{float: left;}
	.ym_hide{display: none;}
	.ym_show{display: block;}
	.slide-image {  width: 100%;  height:100%;}
	.list_horizontal {width: auto; display:inline-block; }
	.voucher_center__1{white-space:normal;width:749upx;height:1510upx;padding:0upx;clear:both;float:left; border-radius:0upx;font-size:8upx;}
	.voucher_center__1 .voucher_center__47{white-space:normal;width:181upx;height:34upx;padding:0upx;clear:both;margin-top:29upx;margin-left:34upx;float:left; border-radius:0upx; color:#646464;font-size:34upx; line-height:34upx;}
	.voucher_center__1 .voucher_center__48{white-space:normal;width:647upx;height:44upx;padding:0upx;clear:both;margin-top:68upx;margin-left:34upx;float:left; border-radius:0upx;font-size:43upx; line-height:44upx;}
	.voucher_center__1 .voucher_center__48 .voucher_center__49{white-space:normal;width:auto;height:44upx;padding:0upx;margin-top:0upx;margin-left:0upx;float:left; border-radius:0upx; color:#646464;font-size:43upx; line-height:44upx;}
	.voucher_center__1 .voucher_center__48 .money{white-space:normal;width:auto;height:44upx;min-height:44upx;padding:0upx;margin-top:0upx;margin-left:25upx;float:left; border-radius:0upx; color:#ff0000;font-size:50upx; line-height:50upx;}
	.voucher_center__1 .payType{white-space:normal;width:683upx;height:50upx;padding:0upx;clear:both;margin-top:102upx;margin-left:33upx;float:left; border-radius:0upx;font-size:49upx; line-height:50upx;}
	.voucher_center__1 .payType .voucher_center__55{white-space:normal;width:46upx;height:47upx;padding:0upx;margin-top:3upx;margin-left:2upx;float:left; border-radius:0upx;font-size:48upx; line-height:47upx;}
	.voucher_center__1 .payType .voucher_center__56{white-space:normal;width:61upx;height:28upx;padding:0upx;margin-top:11upx;margin-left:23upx;float:left; border-radius:0upx; color:#646464;font-size:27upx; line-height:28upx;}
	.voucher_center__1 .payType .voucher_center__57{white-space:normal;width:43upx;height:44upx;padding:0upx;margin-top:2upx;margin-left:4upx;float:left; border-radius:0upx;font-size:43upx; line-height:44upx;}
	.voucher_center__1 .payType .voucher_center__58{white-space:normal;width:47upx;height:47upx;padding:0upx;margin-top:3upx;margin-left:105upx;float:left; border-radius:0upx;font-size:49upx; line-height:47upx;}
	.voucher_center__1 .payType .voucher_center__59{white-space:normal;width:81upx;height:29upx;padding:0upx;margin-top:11upx;margin-left:22upx;float:left; border-radius:0upx; color:#646464;font-size:27upx; line-height:29upx;}
	.voucher_center__1 .payType .voucher_center__60{white-space:normal;width:43upx;height:43upx;padding:0upx;margin-top:3upx;margin-left:11upx;float:left; border-radius:0upx;font-size:42upx; line-height:43upx;}
	.voucher_center__1 .btSubmit{white-space:normal;width:679upx;height:90upx;padding:0upx;clear:both;margin-top:65upx;margin-left:36upx;float:left;background-color:#fd4542;text-align:center;justify-content:center; border-radius:10upx; cursor:pointer; color:#ffffff;font-size:27upx; line-height:90upx;}
	.voucher_center__1 .voucher_center__22{white-space:normal;width:180upx;height:34upx;padding:0upx;clear:both;margin-top:76upx;margin-left:36upx;float:left; border-radius:0upx; color:#646464;font-size:31upx; line-height:34upx;}
	.voucher_center__1 .voucher_center__23{white-space:normal;width:677upx;height:365upx;padding:0upx;clear:both;margin-top:32upx;margin-left:36upx;float:left; border-radius:0upx; color:#c8c8c8;font-size:27upx; line-height:40upx;}
	.voucher_center__1 .voucher_center__66{white-space:normal;width:50%;height:34upx;padding:0upx;clear:both;margin-top:76upx;float:left; border-radius:0upx; color:#646464;font-size:31upx; line-height:34upx;}
</style>